﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Bmz.IM.Communication
{
    public class UdpCommunication
    {
        UdpClient udpClient = null;
        IPEndPoint remoteIpEndPoint = null;
        public UdpCommunication()
        {
            Init(string.Empty, 0, string.Empty, 0);
        }
        public UdpCommunication(string fromIp, int fromPort)
        {
            Init(fromIp, fromPort, string.Empty, 0);
        }

        public UdpCommunication(string fromIp, int fromPort, string toIp, int toPort)
        {
            Init( fromIp,  fromPort,  toIp,  toPort);
        }

        private void Init(string fromIp, int fromPort, string toIp, int toPort)
        {
            if (fromIp == string.Empty)// 匿名模式(套接字绑定的端口由系统随机分配)
                udpClient = new UdpClient(0);
            else
                udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse(fromIp), fromPort));
            if (toIp != string.Empty)
            {
                IPAddress remoteIp = IPAddress.Parse(toIp);
                remoteIpEndPoint = new IPEndPoint(remoteIp, toPort);
            }
        }

        public void SendMessage(string content)
        {
            byte[] sendBytes = Encoding.Unicode.GetBytes(content);
            udpClient.Send(sendBytes, sendBytes.Length, remoteIpEndPoint);
        }

        public void SendMessage(string toIp, int toPort, string content)
        {
            byte[] sendBytes = Encoding.Unicode.GetBytes(content);
            IPAddress remoteIp = IPAddress.Parse(toIp);
            remoteIpEndPoint = new IPEndPoint(remoteIp, toPort);
            udpClient.Send(sendBytes, sendBytes.Length, remoteIpEndPoint);
        }

        public string ReceiveMessage()
        {
            byte[] receiveBytes = udpClient.Receive(ref remoteIpEndPoint);
            return Encoding.Unicode.GetString(receiveBytes);
        }
    }
}
